package com.xy.novelmanagement.controller;

import com.xy.model.Catalog;
import com.xy.model.RestfulResult;
import com.xy.novelmanagement.service.IBQGSpider;
import com.xy.novelmanagement.service.INovelAddService;
import com.xy.utils.FileTypeUtil;
import com.xy.utils.NovelCatalogUtil;
import com.xy.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/novelAdd")
public class NovelAddController {
		@Autowired
		private INovelAddService novelAddService;
		public final String FILEPATHTEMP = "D://JavaFileBox/FileTemp/";
		@Autowired
		private IBQGSpider ibqSpiderService;
		@GetMapping("/{novelName}")
		public RestfulResult getCatalogs(@PathVariable String novelName) {
				if (StringUtils.isEmpty(novelName)) {
						return RestfulResult.failed("-403", "小说名不能为空");
				}
				List<Catalog> catalogList = novelAddService.getCatalogsByName(novelName);
				return RestfulResult.success(catalogList);
		}

		/*
		 * 上传章节文件
		 * */
		@PostMapping("/uploadCatalogFile/")
		public RestfulResult uploadCatalog(@RequestParam("file") MultipartFile file) {
				if (file.isEmpty()) {
						return RestfulResult.failed("-403", "上传失败！请选择上传文件。");
				}
				log.info("uploadCatalog fileName = {}", file.getOriginalFilename());
				String fileName = file.getOriginalFilename();

				File dest = new File(FILEPATHTEMP + fileName);
				try {
						file.transferTo(dest);
						log.info("上传成功");
				} catch (IOException e) {
						log.error(e.toString(), e);
						return RestfulResult.failed("500", "上传失败！");
				}

				return RestfulResult.success("上传成功");
		}

		/*
		 * 添加章节-file
		 * */
		@PostMapping("/addCatalogByFile/{catalogName}")
		public RestfulResult addNewCatalogByFile(@PathVariable String catalogName, @RequestParam String novelName) {
				if (!catalogName.equals("")) {
						String src = FILEPATHTEMP + catalogName + ".txt";
						File file = new File(src);
						if (!file.isFile() || !file.exists()) {
								return RestfulResult.failed("404", "上传的小说文件不存在！");
						}
						FileInputStream fis = null;
						try {
								fis = new FileInputStream(src);
								byte[] bt = new byte[1024];
								int length = -1;
								StringBuffer bf = new StringBuffer();
								while ((length = fis.read(bt)) != -1) {
										bf.append(new String(bt, StandardCharsets.UTF_8));
								}
								log.info("读取文件成功！");
								//log.info(bf.toString());
								//将章节插入数据库
								log.info("开始插入：" + novelName + " 》" + catalogName);
								String result = novelAddService.addCatalogByFile(catalogName, novelName, bf.toString());
								if (result.equals("")) {
										return RestfulResult.success("添加小说《" + novelName + "》的章节{" + catalogName + "}成功！");
								} else {
										return RestfulResult.failed("500", result);
								}
						} catch (Exception e) {
								log.error(e.toString(), e);
								return RestfulResult.failed("500", "添加章节失败！");
						} finally {
								try {
										fis.close();
								} catch (IOException e) {
										e.printStackTrace();
								}
						}
				}
				return RestfulResult.success();
		}

		/*
		 * 添加章节
		 * */
		@PostMapping("/addCatalog/")
		public RestfulResult addNewCatalog(String novelName, String catalogName, String content) {
				log.info("添加章节参数：" + novelName + "》" + catalogName + "》" + content);
				if (novelName == null || novelName.equals("")) {
						return RestfulResult.failed("-403", "小说名不能为空！");
				} else if (catalogName == null || catalogName.equals("")) {
						return RestfulResult.failed("-403", "章节名不能为空！");
				} else if (content == null || content.equals("")) {
						return RestfulResult.failed("-403", "章节内容不能为空！");
				}
				String result = novelAddService.addCatalog(novelName, catalogName, content);

				if (result.equals("")) {
						result = "添加小说《" + novelName + "》的章节{" + catalogName + "}成功！";
				}
				return RestfulResult.success(result);
		}

		/*
		 * 上传小说封面
		 * */
		@PostMapping("/addNovel/img/")
		public void addNovelImg(@RequestParam("imgFile") MultipartFile imgFile) {
				if (imgFile.isEmpty()) {
						log.error("-403", "上传失败！请选择上传文件。");
				}
				try {
						log.info("uploadNovelImg imgName = {}", imgFile.getOriginalFilename());
						String fileName = imgFile.getOriginalFilename();

						File dest = new File(FILEPATHTEMP + fileName);

						imgFile.transferTo(dest);
						log.info("上传成功,文件类型为：" + FileTypeUtil.getFileType(FILEPATHTEMP + fileName));
				} catch (IOException e) {
						log.error("上传失败{}", e.getMessage(), e);
				}
		}

		/*
		 * 上传小说txt文件
		 * */
		@PostMapping("/addNovel/novel/")
		public void addNovelFile(@RequestParam("novelFile") MultipartFile novelFile) {
				if (novelFile.isEmpty()) {
						log.error("-403", "上传失败！请选择上传文件。");
				}
				try {
						log.info("uploadNovelFile novelFileName = {}", novelFile.getOriginalFilename());
						String fileName = novelFile.getOriginalFilename();

						File dest = new File(FILEPATHTEMP + fileName);

						novelFile.transferTo(dest);
						log.info("上传成功,文件类型为：" + FileTypeUtil.getFileType(FILEPATHTEMP + fileName));
				} catch (IOException e) {
						log.error("上传失败{}", e.getMessage(), e);
				}
		}

		/*
		 * 添加小说
		 * */
		@PostMapping("/addNovel/")
		public RestfulResult addNovel(HttpServletRequest request) {
				String novelName = request.getParameter("novelName");
				String novelType = request.getParameter("novelType");
				String author = request.getParameter("author");
				String intro = request.getParameter("intro");
				String fileName = request.getParameter("fileName");
				String imgName = request.getParameter("imgName");

				log.info("开始添加小说！novel：{}", novelName + " " + novelType + " " + author + " " + intro + " " + fileName + " " + imgName);
				//判断上传文件是否为空或类型错误
				if (fileName == null || fileName.equals("") || (!(new File(FILEPATHTEMP + fileName).exists()))) {
						log.info("添加小说失败，小说文件不能为空");
						return RestfulResult.failed("-403", "小说文件不能为空");
				} else if (!"txt".equals(fileName.substring(fileName.indexOf('.')).replace(".",""))) {
						log.info("添加小说失败，小说文件类型错误");
						return RestfulResult.failed("500", "小说文件类型错误！");
				} else if (!(new File(FILEPATHTEMP + fileName).exists())||imgName == null || imgName.equals("")) {
						log.info("添加小说失败，小说封面不能为空");
						return RestfulResult.failed("-403", "小说封面不能为空");
				} else if (!"jpg".equals(FileTypeUtil.getFileType(FILEPATHTEMP + imgName))) {
						log.info("封面类型："+FileTypeUtil.getFileType(FILEPATHTEMP + imgName));
						 if ( !"png".equals(FileTypeUtil.getFileType(FILEPATHTEMP + imgName)) ) {
								log.info("添加小说失败，png小说封面文件类型错误");
								return RestfulResult.failed("500", "小说封面文件类型错误！");
						}
				}  else if ("".equals(novelName) || "".equals(novelType) || "".equals(author) || "".equals(intro)) {
						log.info("添加小说失败，小说基本信息不能为空");
						return RestfulResult.failed("-403", "小说基本信息不能为空！");
				}
				try {
						//将小说图片和文件拷贝到指定目录
						FileUtils.copyFile(new File(FILEPATHTEMP + fileName), new File(PropertiesUtil.getValue("txtDir","D:/JavaFileBox/txt/") + fileName));
						FileUtils.copyFile(new File(FILEPATHTEMP + imgName), new File(PropertiesUtil.getValue("imgDir","D:/JavaFileBox/picture/") + imgName));
						//解析小说文件，提取目录
						Map<String, List<String>> catalogs = NovelCatalogUtil.getCatalogs(FILEPATHTEMP + fileName);
						//将章节信息和小说信息保存到数据库
						String resultMsg = novelAddService.saveNovel(novelName, author, intro, novelType, catalogs);
						if (!resultMsg.equals("添加小说成功!")) {
								return RestfulResult.failed("500", resultMsg);
						}
				} catch (IOException e) {
						e.printStackTrace();
				}
				return RestfulResult.success("添加小说成功!");
		}

		/*
		* 获取笔趣阁分类
		* */
		@GetMapping("/BQG/type/")
		public RestfulResult getBQGType(){
				List<String> list = ibqSpiderService.getTyps();
				return RestfulResult.success(list);
		}
}
